package messenger;

import java.util.logging.Logger;

public class ReceiveMessageDeamon extends Thread {
	
	private MainWindow frame = null;
	private MessengerClient client = null;
	private Logger log = Logger.getLogger("ReceiveMessageDeamon");
	
	public ReceiveMessageDeamon(MainWindow f, MessengerClient c) {
		frame = f;
		client = c;
	}
	
	private static final int WAIT = 500;
	
	public void waitInterval(long i) {
		try {
			Thread.sleep(i*WAIT);
		} catch (InterruptedException e) {
			
		}
	}
	
	@Override
	public void run() {
		super.run();
		while(true) {
			String msg = client.receiveMessage();
			log.info("get Message:[" + msg + "]");
			if(!client.isValidMessage(msg)) {
				continue;
			}
			String[] tmps = msg.split(MessengerSession.N_SPLIT1);
			if(tmps.length != 5) {
				continue;
			}
			String action = tmps[0];
			String to = tmps[1];
			String from = tmps[2];
			String type = tmps[3];
			String message = tmps[4];
			if(MessengerSession.A_GET_FRIEND.equals(action)) {
				String[] friendArray = null;
				if(message.trim().length() > 0) {
					friendArray = message.split(MessengerSession.N_SPLIT2);
				}
				frame.refreshFriendList(friendArray);
			}else if(MessengerSession.A_SEND_MESSAGE.equals(action)) {
				ChatDialog messenger = frame.getMessenger(from);
				if(messenger != null) {
					messenger.getCP().appendMessage(message);
				} else {
					messenger = new ChatDialog(client, frame, from);
					frame.addMessenger(from, messenger);
					messenger.getCP().appendMessage(message);
					messenger.setVisible(true);
					
				}
			}
		}
	}
}
